//
//  JieXiaoDingdanDetail.swift
//  HappyEat
//
//  Created by 张继强 on 17/1/23.
//  Copyright © 2017年 陌路是我. All rights reserved.
//

import UIKit
import SwiftyJSON

class JieXiaoDingdanDetail: UIViewController ,UITableViewDelegate,UITableViewDataSource,ShowCountCellDelegate{
    
    let CountCellId:String = "CountCellId"
    
    let MineSetStyleCellId:String = "CellId"
    
    let XiangYaDuihuanCellId:String = "XiangYaDuiHuanCellId"
    
    let netRequst:NetworkRequest = NetworkRequest.shareInstance
    
    var stringTool:CodingStrinTool = CodingStrinTool.shareInstance
    
    var detaiModel:ProductDetailModel?
    //购买份数的全局变量
    var buyCountString:String = "10"
    
    var payInfoModel:UserPayInfoModel?
//    var tableView:UITableView?{
//        return UITableView.init()
//    }
    var tableView:UITableView = UITableView.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.createUi()
        //获取支付信息
        self.getPayInfoAction()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setNav()
    }
}
extension JieXiaoDingdanDetail{
    func setNav(){
        self.navigationItem.title = "商品详情"
        self.navigationController?.navigationBar.subviews.first?.alpha = 0.0
        UIApplication.shared.setStatusBarStyle(.default, animated: true)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "", imagStr: "ic_back", fontSize: 14, target: self, action: #selector(leftButtonAction))
    }
    func leftButtonAction(){
        self.navigationController!.popViewController(animated: true)
    }
    func createUi(){
       self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints({ (make) in
            make.left.equalTo(0)
            make.top.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
        })
        let footView:UIView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: k_Wide, height: 64))
        
        self.tableView.tableFooterView = footView
        let duihuanButton:UIButton = UIButton.init()
        footView.addSubview(duihuanButton)
        duihuanButton.snp.makeConstraints { (make) in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(12)
            make.height.equalTo(40)
        }
        duihuanButton.layer.cornerRadius = 3.0
        duihuanButton.backgroundColor = .red
        duihuanButton.setTitleColor(.white, for: .normal)
        duihuanButton.setTitle("确认兑换", for: .normal)
        duihuanButton.addTarget(self, action: #selector(duiHUanAction), for: .touchUpInside)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(ShowCountCell.self, forCellReuseIdentifier: CountCellId)
        self.tableView.register(MineSetSwitchCell.self, forCellReuseIdentifier: MineSetStyleCellId)
        self.tableView.register(XiangyaDuihuanCell.self , forCellReuseIdentifier: XiangYaDuihuanCellId)
    }
    //MARK:获取支付信息
    func getPayInfoAction(){
//        post参数：productSeriesId：该期商品id
        guard let phoneNum:String = UserDefaults.standard.object(forKey: PHONE) as! String? else{
            return
        }
        let passWord:String = UserDefaults.standard.object(forKey: PASSWWORD) as! String? ?? ""
        var miStr:String = phoneNum + ":" + passWord
        miStr = self.stringTool.base64Encoding(plainString: miStr)
        let params = ["productSeriesId":self.detaiModel!.productSeriesId ?? ""]
        self.netRequst.postRequest(urlString: GetPayInfo_URL, params: params, headerStr: miStr, success: { [weak self](success) in
            print(success)
            let returnDic = JSON(success)
            //成功操作
            if returnDic["status"] == "SUCCESS" {
                self?.payInfoModel = UserPayInfoModel.init(data: returnDic["data"])
                print(self?.payInfoModel)
                self?.tableView.reloadData()
            }else {
                //数据错误
            }
            })
        { (error) in
            print(error)
        }
    }
    //MARK:兑换Action
    func duiHUanAction(){
       //购买商品Url
        if self.buyCountString == nil {
            return
        }
        //        post参数：productSeriesId：该期商品id
        guard let phoneNum:String = UserDefaults.standard.object(forKey: PHONE) as! String? else{
            return
        }
        let passWord:String = UserDefaults.standard.object(forKey: PASSWWORD) as! String? ?? ""
        var miStr:String = phoneNum + ":" + passWord
        miStr = self.stringTool.base64Encoding(plainString: miStr)
        let params = ["productSeriesId":self.detaiModel?.productSeriesId ?? "",
                      "num":self.buyCountString ?? "",
                      "userCouponId":""]
        self.netRequst.postRequest(urlString: BuyProduct_URL, params: params, headerStr: miStr, success: {
            [weak self]
            (success) in
            let returnDic = JSON(success)
            if returnDic["status"] == "SUCCESS" {
                //操作成功
                //刷新个人中心界面
                print(success)
            }else{
                //操作失败,输出logo信息
            }
        })
        { (error) in
                print(error)
        }
    }
    //MARK:第一个Cell的代理方法实现
    func returnBuyNumCount(_ countStr: String) {
            self.buyCountString = countStr
    }
    //MARK:UITableViewDelegate
    @objc(tableView:didSelectRowAtIndexPath:) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected")
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    @objc(numberOfSectionsInTableView:) func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    @objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell:ShowCountCell = tableView.dequeueReusableCell(withIdentifier: CountCellId) as! ShowCountCell
            cell.delegate = self
            return cell
        }else if indexPath.section == 1{
            let cell:MineSetSwitchCell = tableView.dequeueReusableCell(withIdentifier: MineSetStyleCellId) as! MineSetSwitchCell
            cell.cellStyle = .rightAllStyle
            cell.leftLabel.text = "优惠券"
            cell.rightLabel.text = "\(self.payInfoModel?.userCoupons?.count ?? 0)张可用"
            return cell
        }else if indexPath.section == 2{
            let cell:MineSetSwitchCell = tableView.dequeueReusableCell(withIdentifier: MineSetStyleCellId) as!MineSetSwitchCell
            cell.cellStyle = .rightAllStyle
            cell.leftLabel.text = "兑换方式"
            cell.rightLabel.isHidden = true
            cell.icon_right.isHidden = true
            cell.backgroundColor = BackGroundColor
            return cell
        }
        let cell:XiangyaDuihuanCell = tableView.dequeueReusableCell(withIdentifier: XiangYaDuihuanCellId) as!XiangyaDuihuanCell
        cell.titileLabel.text = "象牙兑换余额:" + ((self.payInfoModel?.userBalance) ?? "0") + "象牙"
        return cell
    }
    @objc(tableView:heightForRowAtIndexPath:) func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0{
            return 127.5+40
        }
        return 50
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 8
        }else{
            return 0.001
        }
    }
}
